<?php
class MemSession extends Object{
    private static $handler=null;
    private static $lifetime=null;
    
    public function __construct(){
        $this->MemSession();
    }
    
    public function MemSession(){
        #TODO
    }
    
    
    public static function start(Memcache $memcache){
        ini_set('session.save_handler', 'user');
        
        self::$handler=$memcache;
        self::$lifetime=ini_get('session.gc_maxlifetime');
        session_set_save_handler(
            array(__CLASS__,'open'),
            array(__CLASS__,'close'),
            array(__CLASS__,'read'),
            array(__CLASS__,'write'),
            array(__CLASS__,'destroy'),
            array(__CLASS__,'gc')
        );
        self::$handler->flush();
        session_start();
        return true;
    }
    
    public static function open($path,$name){
        return true;
    }
    
    public static function close(){
        return true;
    }
    
    //从session中读取数据
    public static function read($PHPSESSID){
        $out=self::$handler->get(self::session_key($PHPSESSID));
        if ($out===false || is_null($out))
            return '';

        return $out;
    }
    
    public static function write($PHPSESSID,$data){
        $method=$data?'set':'replace';
        return self::$handler->$method(self::session_key($PHPSESSID),$data,MEMCACHE_COMPRESSED,self::$lifetime);
    }
    
    public static function destroy($PHPSESSID){
        return self::$handler->delete(self::session_key($PHPSESSID)); 
    }
    //memcache有自己的回收机制
    public static function gc($lifetime){
       return true;#TODO
    }
    
    
    private static function session_key($PHPSESSID){
        $session_key=DB_PREFIX.$PHPSESSID;
        return $session_key;
    }




}